package com.renwei.yunlong.activity.me;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.PasswordForGetBean;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.utils.CommonUtils;
import com.zyf.fwms.commonlibrary.utils.FormatUtil;
import com.zyf.fwms.commonlibrary.utils.SharedPreUtil;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.lang.ref.WeakReference;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 忘记密码页面
 * <p>
 * Created by Administrator on 2017/8/22.
 */

public class PasswordForgetActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener {


    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_right)
    TextView tvRight;
    @Bind(R.id.et_phone)
    EditText etPhone;
    @Bind(R.id.view_phone)
    View viewPhone;
    @Bind(R.id.et_verification)
    EditText etVerification;
    @Bind(R.id.btn_vercode)
    Button btnVercode;
    @Bind(R.id.et_pwd)
    EditText etPwd;
    @Bind(R.id.view_pwd)
    View viewPwd;
    @Bind(R.id.et_determine_pwd)
    EditText etDeterminePwd;
    @Bind(R.id.btn_determine)
    Button btnDetermine;
    private PasswordHandler myHandler = new PasswordHandler(this);
    private String selectCompanyType = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_forget_pwd);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        selectCompanyType = getIntent().getStringExtra("companyType") == null ? "0" : getIntent().getStringExtra("companyType");
        initData();
    }

    private void initData() {
        tvTitle.setText("忘记密码");
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(this);
        btnVercode.setOnClickListener(this);
        btnDetermine.setOnClickListener(this);
        etPwd.setHint(Html.fromHtml("设置密码  <font><small>6~12位数字、字母的组合</small></font>"));
        etDeterminePwd.setHint(Html.fromHtml("确认密码   <font><small>6~12位数字、字母的组合</small></font>"));

        etPwd.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20), AppHelper.emojiFilter});
        etDeterminePwd.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20), AppHelper.emojiFilter});
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_vercode:
                getCode();
                break;
            case R.id.btn_determine:
                check2ForgetPwd();
                break;
            default:
                break;
        }
    }

    //获取忘记密码验证码
    private void getCode() {
        String phone = etPhone.getText().toString().trim();
        if (!FormatUtil.isMobileNO(phone)) {
            showCenterInfoMsg("请输入正确的手机号码");
            return;
        }
        if (!TextUtils.isEmpty(phone)) {
            ServiceRequestManager.getManager().getForgetPwdCode(this, selectCompanyType, phone, this);
            sendMessageClick();//发送验证码
        }
    }

    //修改密码
    private void check2ForgetPwd() {
        String mobilePhone = etPhone.getText().toString().trim();
        String vercode = etVerification.getText().toString().trim();
        String dPwd = etDeterminePwd.getText().toString().trim();
        String pwd = etPwd.getText().toString().trim();
        if (!FormatUtil.isMobileNO(mobilePhone)) {
            showCenterInfoMsg("请输入正确手机号");
            return;
        }
        if (TextUtils.isEmpty(vercode)) {
            showCenterInfoMsg("请输入验证码");
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            showCenterInfoMsg("请输入密码");
            return;
        }
        if (TextUtils.isEmpty(dPwd)) {
            showCenterInfoMsg("请输入确认密码");
            return;
        }
        if (!pwd.equals(dPwd)) {
            showCenterInfoMsg("两次输入密码的不匹配");
            return;
        }
        if (!FormatUtil.isPasswordFormat(dPwd)) {
            showCenterInfoMsg("密码格式不正确,密码限制在6-12位数字、字母的组合");
            return;
        }
        HashMap map = new HashMap();
        map.put("mobilePhone", mobilePhone);
        map.put("newPwd", pwd);
        map.put("vercode", vercode);
        ServiceRequestManager.getManager().forgetPassword(this, this.selectCompanyType, JsonMapUtil.mapToJson(map), this);
    }

    @Override
    public void onSuccess(int requestId, String result) {
        LogUtil.e("忘记密码页面   requestId :" + requestId + "result:" + result);
        PasswordForGetBean bean = new Gson().fromJson(result, PasswordForGetBean.class);
        switch (requestId) {
            case 7://业主修改密码
                bean = new Gson().fromJson(result, PasswordForGetBean.class);
                if (bean != null && bean.getMessage() != null) {
                    if (bean.getMessage().getCode() == 200) {
                        showCenterSuccessMsg("修改成功");
                        SharedPreUtil.saveString(this, "owner_mobile", etPhone.getText().toString().trim());
                        SharedPreUtil.saveString(this, "owner_pwd", String.valueOf(etDeterminePwd.getText().toString().trim()));
                        SharedPreUtil.saveString(this, "default_company_type", String.valueOf(selectCompanyType));
                        this.finish();
                    } else {
                        showCenterInfoMsg(StringUtils.value(bean.getMessage().getMessage()));
                    }
                }
                break;
            case 8://商户修改密码
                bean = new Gson().fromJson(result, PasswordForGetBean.class);
                if (bean != null && bean.getMessage() != null) {
                    if (bean.getMessage().getCode() == 200) {
                        showCenterSuccessMsg("修改成功");
                        SharedPreUtil.saveString(this, "service_mobile", etPhone.getText().toString().trim());
                        SharedPreUtil.saveString(this, "service_pwd", String.valueOf(etDeterminePwd.getText().toString().trim()));
                        SharedPreUtil.saveString(this, "default_company_type", String.valueOf(selectCompanyType));
                        finish();
                    } else {
                        showCenterInfoMsg(StringUtils.value(bean.getMessage().getMessage()));
                    }
                }
                break;
            case 9://业主获取忘记密码验证码
                if (bean.getMessage().getCode() == 200) {
                    showCenterSuccessMsg("已发送");
                } else {
                    showCenterInfoMsg("账号不存在");
                }
                break;
            case 10://商户获取忘记密码验证码
                bean = new Gson().fromJson(result, PasswordForGetBean.class);
                if (bean.getMessage().getCode() == 200) {
                    showCenterSuccessMsg("已发送");
                } else {
                    showCenterInfoMsg("账号不存在");
                }
                break;
            default:
                break;
        }

    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getResources().getString(R.string.net_work_error));
    }


    /**
     * 使用Handler
     * <p>
     * 静态内部类：避免内存泄漏
     */
    private class PasswordHandler extends Handler {
        private final WeakReference<PasswordForgetActivity> weakReference;

        public PasswordHandler(PasswordForgetActivity activity) {
            weakReference = new WeakReference<PasswordForgetActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            PasswordForgetActivity activity = weakReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case 0:
                        try {
                            if (msg.arg1 == 0) {
                                btnVercode.setText("获取验证码");
                                btnVercode.setBackgroundColor(Color.parseColor("#689df8"));
                                btnVercode.setTextColor(Color.parseColor("#FFFFFF"));
                                btnVercode.setClickable(true);
                            } else {
                                btnVercode.setText("(" + msg.arg1 + ")秒");
                                btnVercode.setBackgroundColor(Color.parseColor("#b8bfcc"));
                                btnVercode.setClickable(false);
                            }
                        } catch (Exception e) {
                            LogUtil.e(e.getMessage());
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

    /**
     * 监听按钮下直接调用即可
     */
    private void sendMessageClick() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 59; i >= 0; i--) {
                    Message msg = myHandler.obtainMessage();
                    msg.arg1 = i;
                    myHandler.sendMessage(msg);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public static void openForgetPwdActivity(Context context, String companyTypeStr) {
        Intent intent = new Intent(context, PasswordForgetActivity.class);
        intent.putExtra("companyType", companyTypeStr);
        context.startActivity(intent);
    }
}
